package com.sojson.util.agent;

import javax.servlet.http.HttpServletRequest;

import eu.bitwalker.useragentutils.UserAgent;
import lombok.Data;

/**
 * 用户来源信息工具类
 * 
 * @author liu
 * @date 2021-03-18
 */
public class UserAgentUtil {

    public static final String USER_AGENT_KEY = "user-agent";
    private static final UserAgentUtil USER_AGENT_UTIL = new UserAgentUtil();

    public static Agent getAccountAgent() {
        return USER_AGENT_UTIL.new Agent();
    }

    /**
     * 用户来源信息
     * 
     * @author liu
     * @date 2021-03-18
     */
    @Data
    public class Agent {

        /** 登录IP地址 */
        private String ipaddr;
        /** 登录地点 */
        private String loginLocation;
        /** 浏览器类型 */
        private String browser;
        /** 操作系统 */
        private String os;

        public Agent() {
            HttpServletRequest request = ServletUtil.getHttpServletRequest();
            UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader(USER_AGENT_KEY));
            setIpaddr(IpUtil.getIpAddr(request));
            setLoginLocation(AddressUtil.getRealAddressByIP(getIpaddr()));
            setBrowser(userAgent.getBrowser().getName());
            setOs(userAgent.getOperatingSystem().getName());
        }

        public Agent(UserAgent userAgent) {
            setIpaddr(IpUtil.getIpAddr(ServletUtil.getHttpServletRequest()));
            setLoginLocation(AddressUtil.getRealAddressByIP(getIpaddr()));
            setBrowser(userAgent.getBrowser().getName());
            setOs(userAgent.getOperatingSystem().getName());
        }

        public Agent(String ipaddr, String loginLocation, String browser, String os) {
            this.ipaddr = ipaddr;
            this.loginLocation = loginLocation;
            this.browser = browser;
            this.os = os;
        }

    }

}